package com.xhwl.data.config;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.sdata.AdminAccount;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.data.util.RedisUtils;
import com.xhwl.data.util.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 10:16 2022/6/29
 */
@Component
public class WebAdminAccountArgResolver implements WebArgumentResolver {

    private static final Logger log = LoggerFactory.getLogger(WebAccountArgResolver.class);

//    public static final String ADMIN_TOKEN_PREFIX = "TOKEN_ADMIN_";

    private String ACCOUNT_SAVE_PREFIX = "ADMIN_USERINFO_";

    @Override
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest nativeWebRequest) {
        if (null != methodParameter.getParameterType() && methodParameter.getParameterType().equals(AdminAccount.class)) {
            HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
            //来自网关解析token后，往请求头新增的userId
            String userId = request.getHeader("userId");
            if (StringUtils.isEmpty(userId)){
                return null;
            }
            String appId = request.getHeader("appId");
            if(StringUtils.isEmpty(appId)){
                return null;
            }
            RedisUtils redisUtils = SpringContextUtils.getBean(RedisUtils.class);
            Object accountInfo = redisUtils.get(appId + "_" + ACCOUNT_SAVE_PREFIX + userId);
            if (Objects.nonNull(accountInfo)) {
                AdminAccount adminAccount = conversionAccount((JSONObject) accountInfo);
                return adminAccount;
            }else{
                log.info("不存在当前admin账号的登录信息，userId={}", userId);
                return null;
            }
        }
        return UNRESOLVED;
    }


    /**
     * 转换自动注入的账号数据
     *
     * @param jsonObject
     * @return
     */
    private AdminAccount conversionAccount(JSONObject jsonObject) {
        AdminAccount account = new AdminAccount();
        account.setId((Integer) jsonObject.get("userId"));
        account.setLoginName(jsonObject.getString("loginName"));
        account.setPassword(jsonObject.getString("password"));
        account.setName(jsonObject.getString("name"));
        account.setIsDeleted(jsonObject.getBoolean("isDeleted"));
        account.setUpdateAt((Date) jsonObject.get("updatedAt"));
        account.setCreateAt((Date) jsonObject.get("createdAt"));
        return account;
    }
}
